<template>
  <div>
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phoneNumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期时间"
              end-placeholder="结束日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="handleTimeChange"
              :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div class="operation-serviceRegion">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增用户
      </el-button>
    </div>
    <!-- 数据表格 -->
    <el-card>
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="phoneNumber" label="手机号" width="180"></el-table-column>
        <el-table-column prop="displayName" label="账户显示名" width="120"></el-table-column>
        <el-table-column prop="roleNames" label="角色" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
              {{ scope.row.status === true ? '正常' : '冻结' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建人" width="120"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="150"
                         :formatter="(row,col) => formatTime(row[col.property])"></el-table-column>
        <el-table-column prop="updater" label="更新人" width="150"></el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="160"
                         :formatter="(row,col) => formatTime(row[col.property])"></el-table-column>


        <el-table-column label="操作" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                :type="scope.row.status === true ? 'danger' : 'success' "
                @click="updateStatus(scope.row)"
            >{{ scope.row.status === true ? '冻结' : '恢复正常' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          class="pagination"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetForm"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="120px"
      >
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="formData.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="账户显示名" prop="displayName">
          <el-input v-model="formData.displayName"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select
              v-model="formData.roleIds"
              multiple
              filterable
              remote
              style="width:100%"
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="loading">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="formData.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">冻结</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getInfo, add, update, updateStatus} from '@/api/userAccount'
import {selList} from '@/api/role'
import moment from 'moment';

export default {
  data() {
    return {
      searchForm: {
        phone: '',
        timeRange: []
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      tableData: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增用户',
      formData: {
        phoneNumber: '',
        displayName: '',
        roleIds: '',
        status: 1
      },
      rules: {
        phoneNumber: [{required: true, message: '请输入手机号', trigger: 'blur'},
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入11位有效手机号',
            trigger: 'blur'
          }],
        displayName: [{required: true, message: '请输入账户显示名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        confirmPassword: [
          {required: true, message: '请输入确认密码', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value !== this.formData.password) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    remoteMethod(query) {
      console.log(1212)
      if (query !== '') {
        this.loading = true;
        selList(query).then(res => {
          console.log(res)
          this.loading = false;
          this.options = res.data

        }).catch(() => {
        })
      } else {
        this.options = [];
      }
    },
    handleTimeChange(val) {
      this.searchForm.timeRange = val
      console.log('选择的时间范围:', val)
      // 这里可以触发查询或其他操作
    },
    formatTime(date) {
      console.log(date)
      return moment(date).format('YYYY-MM-DD HH:mm:ss');
    },
    fetchData() {
      this.loading = true
      getInfo(this.pagination.currentPage, this.pagination.pageSize, this.searchForm).then(res => {
        // login(this.formData).then(res => {
        console.log(res)
        this.loading = false
        if (res.code === 200) {
          this.pagination.total = res.data.total
          this.tableData = res.data.recordList
        }
        // 处理登录成功逻辑
      }).catch(err => {
        this.loading = false
        console.log(err)
        // 错误已在拦截器统一处理
      })
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        phone: '',
        timeRange: []
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑服务区域'
      this.formData = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    handleDelete() {
      this.$confirm('确认删除该服务区域吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.fetchData()
      }).catch(() => {
      })
    },
    updateStatus(row) {
      updateStatus({id: row.id}).then(res => {
        if (res.code === 200) {
          console.log(res)
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.fetchData()
        }
      })
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let id = this.formData.id
          if (id !== undefined && id !== '') {
            update(this.formData).then(res => {
              if (res.code === 200) {
                console.log(res)
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.fetchData()
              }
            })
          } else {
            add(this.formData).then(res => {
              if (res.code === 200) {
                console.log(res)
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.fetchData()
              }

            })
          }


        }
      })
    },
    resetForm() {
      this.$refs.formRef.resetFields()
      this.formData = {
        phoneNumber: '',
        displayName: '',
        roleIds: '',
        status: 1
      }
    }
  }
}
</script>

<style scoped>
.service-phone-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-top: 10px;
}

.operation-serviceRegion {
  margin-bottom: 20px;
}

.operation-phone {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
